var selectedAppRow = null, selectedDataRow = null;

$(function () {
    newCheck.initByName('error_text');
    newCheck.initByName('del_text');
    initTextSearch("#pDeptName", basePath + 'basicDoctorInfo/getPDeptList?t=' + (new Date()).getTime() + '&name=', ['deptCode', 'deptName'], {
        'deptCode': '科室编码',
        'deptName': '科室名称'
    }, 'deptCode', 'deptName', true, selectPDeptValue, pDeptChange);
    initTextSearchWithParam("#cDeptName", basePath + 'basicDoctorInfo/getCDeptList?t=' + (new Date()).getTime(), ['deptCode', 'deptName'], {
        'deptCode': '科室编码',
        'deptName': '科室名称'
    }, 'deptCode', 'deptName', true, selectCDeptValue, cDeptChange, getPDeptCode);
    initTextSearch("#orgName", basePath + 'basicDoctorInfo/getOrgList?t=' + (new Date()).getTime() + '&name=', ['orgName', 'orgCode'], {
        'orgName': '机构名称',
        'orgCode': '编码'
    }, 'orgCode', 'orgName', true, selectOrgValue, orgChange);
    initTextSearch("#isvPidName", basePath + 'basicDoctorInfo/getIsvList?t=' + (new Date()).getTime() + '&name=', ['isvPid', 'isvName'], {
        'isvPid': 'isvPid',
        'isvName': '服务商名称'
    }, 'isvPid', 'isvName', true, selectIsvValue, isvChange);

     initScanQrCodePage('minApp', 'publish', doPublishApp,closeScanOrCodePage,refreshQrCode);
});


function pDeptChange() {
    //清空值
    $('#pDeptCode').val("");
    //修改一级时，清空二级
    $('#cDeptCode').val("");
    $('#cDeptName').val("");
}

function selectPDeptValue(data) {
    //联动赋值
    if (data && data.deptCode && data.deptCode != '') {
        $('#pDeptCode').val(data.deptCode);
    }
    //修改一级时，清空二级
    $('#cDeptCode').val("");
    $('#cDeptName').val("");
    doWinRefresh();
}

function cDeptChange() {
    //清空值
    $('#cDeptCode').val("");
}

function selectCDeptValue(data) {
    //联动赋值
    if (data && data.deptCode && data.deptCode != '') {
        $('#cDeptCode').val(data.deptCode);
    }
    doWinRefresh();
}

function getPDeptCode() {
    var pDeptCode = $('#pDeptCode').val();
    return {
        t: new Date().getTime(),
        name: $("#cDeptName").val(),
        parentCode: pDeptCode
    };
}

function orgChange() {
    //清空值
    $('#orgCode').val("");
}

function selectOrgValue(data) {
    //联动赋值
    if (data && data.orgCode && data.orgCode != '') {
        $('#orgCode').val(data.orgCode);
    }
    doWinRefresh();
}

function isvChange() {
    //清空值
    $('#isvPid').val("");
}

function selectIsvValue(data) {
    //联动赋值
    if (data && data.isvPid && data.isvPid != '') {
        $('#isvPid').val(data.isvPid);
    }
    doWinRefresh();
}


var selcetIsv = null, pselcetIsv = null;

function getPSelected(data) {
    pselcetIsv = data;
    doWinRefresh();
}


function doAppRefresh() {
    $('#dataAppTable').bootstrapTable('refresh', {
        url: basePath + 'bizApp/getGridBizAppPublishData?t=' + new Date().getTime(),
    });
}


function getAppParams(params) {
    // 业务编码
    $("#sbizCode").val("");
    // 机构编码
    $("#sorgCode").val("");
    // 服务商编码
    $("#sisvPid").val("");
    var postData = {
        pageSize: params.pageSize,
        pageNo: params.pageNumber
    };
    postData[$("#selectType").val()] = $.trim($("#search").val());
    postData.appCategory = 'org';
    postData.isParent = '1';
    selectedAppRow = null;
    return postData;
}

$("#dataAppTable").on("click-row.bs.table", function (e, row, $element) {
    $("#dataAppTable .success").removeClass("success");
    $element.addClass("success");
    selectedAppRow = row;
    // doLogRefresh();
    // 查询条件的赋值
    $("#sbizCode").val(selectedAppRow.bizCode);
    $("#sorgCode").val(selectedAppRow.refCode);
    $("#sisvPid").val(selectedAppRow.isvPid);
    doRefresh();
});


function doRefresh() {
    if (selectedAppRow == null) {
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    selectedDataRow = null;
    $('#dataTable').bootstrapTable('refresh', {
        url: basePath + 'bizApp/getGridDocBizAppData?t=' + new Date().getTime(),
    });
}

var isInit = true;

function getParams(params) {
    var postData = {};
    if (isInit) {
        isInit = false;
        postData.pageSize = searchInfo.pageSize ? searchInfo.pageSize : params.pageSize;
        postData.pageNo = searchInfo.pageNo ? searchInfo.pageNo : params.pageNumber;
    } else {
        postData.pageSize = params.pageSize;
        postData.pageNo = params.pageNumber;
    }
    $("#searchForm").serializeArray().map((function (item, index, input) {
        postData[item.name] = item.value;
    }));
    // 业务编码
    postData.bizCode = $("#sbizCode").val();
    // 机构编码
    postData.orgCode = $("#sorgCode").val();
    // 服务商编码
    postData.isvPid = $("#sisvPid").val();
    postData.appCategory = 'doctor';
    postData.isParent = '1';
    return postData;
}


$("#dataTable").on("click-row.bs.table", function (e, row, $element) {
    $("#dataTable .success").removeClass("success");
    $element.addClass("success");
    selectedDataRow = row;
});

function selectChange() {
    var selectType = $("#selectType").val();
    switch (selectType) {
        case 'orgName': {
            $("#search").attr("name", selectType);
            $("#search").attr("placeholder", "输入机构名称");
            break;
        }
            ;
        case 'bizName': {
            $("#search").attr("name", selectType);
            $("#search").attr("placeholder", "输入业务类型");
            break;
        }
            ;
        case 'isvName': {
            $("#search").attr("name", selectType);
            $("#search").attr("placeholder", "输入服务商名称");
            break;
        }
            ;
    }
}

var VueObj = new Vue({
    el: "#VueObj",
    data: {addBizApp: {}, editBizApp: {}}
});

function add() {
    if (selectedAppRow == null) {
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    VueObj.$set(VueObj.$data, "addBizApp", JSON.parse(JSON.stringify(selectedAppRow)));
    // 置空
    $("#isvPid").val("");
    $("#isvPidName").val("");

    $("#orgCode").val("");
    $("#orgName").val("");

    $("#cDeptCode").val("");
    $("#cDeptName").val("");

    $("#pDeptCode").val("");
    $("#pDeptName").val("");

    $("#ddocName").val("");
    // 查询
    doWinRefresh();
    $('#addBizApp').modal(true);
}

function doSaveApp() {
    if (selectedAppRow == null) {
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    var selectRows = getSelectedRows("#WinTable");
    if (selectRows == null || selectRows.length == 0) {
        toastr.error("请选择专家");
        return;
    }
    console.log(selectRows);
    var list = new Array();
    //这是父类的
    if (selectedAppRow.reqBizCode != null) {
        var reqBizCode = selectedAppRow.reqBizCode.split(",");
        console.log(reqBizCode);
        var reqBizName = selectedAppRow.reqBizName.split(",");
        console.log(reqBizName);
    }

    if (selectRows != null && selectRows.length != 0) {
        for (var index in selectRows) {
            list.push({
                refCode: selectRows[index].docCode,
                appName: selectedAppRow.bizName,
                appDisplayName: selectedAppRow.bizName,
                bizCode: selectedAppRow.bizCode,
                sortNum: selectRows[index].sortNum,
                status: 'unpublished',
                appCategory: 'doctor'
            });
            if (reqBizCode != null && reqBizCode.length != 0)
                for (var page in reqBizCode) {
                    list.push({
                        refCode: selectRows[index].docCode,
                        appName: reqBizName[page],
                        appDisplayName: reqBizName[page],
                        sortNum: selectRows[index].sortNum,
                        bizCode: reqBizCode[page],
                        status: 'publish',
                        appCategory: 'doctor'
                    });
                }
        }
    }

    $.ajax({
        type: 'post',
        url: basePath + 'bizApp/addDocBizApp',
        dataType: 'json',
        contentType: "application/json",
        beforeSend: function () {
            showLoading();
        },
        complete: function () {
            hideLoading();
        },
        data: JSON.stringify({
            isvPid: selectedAppRow.isvPid,
            orgCode: selectedAppRow.refCode,
            refDataList: list,
            appCategory: 'doctor'
        }),
        success: function (data) {
            if (data.result) {
                toastr.success(data.message);
                doRefresh();
                $("#addBizApp").modal('hide');
            } else {
                toastr.error(data.message);
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });

}


function doWinRefresh() {
    $('#WinTable').bootstrapTable('refresh', {
        url: basePath + 'bizApp/getGridDocInfoPublishData?t=' + new Date().getTime(),
    });
}


function getWinParams(params) {
    var postData = {
        pageSize: params.pageSize,
        pageNo: params.pageNumber
    };
    // 业务编码
    postData.bizCode = selectedAppRow.bizCode;
    // 机构编码
    postData.appOrgCode = selectedAppRow.refCode;
    // 服务商编码
    postData.appIsvPid = selectedAppRow.isvPid;
    // 查询条件
    postData.isvPid = $.trim($("#isvPid").val());
    postData.orgCode = $.trim($("#orgCode").val());
    postData.cDeptCode = $.trim($("#cDeptCode").val());
    postData.pDeptCode = $.trim($("#pDeptCode").val());
    postData.docName = $.trim($("#ddocName").val());
    postData.appCategory = 'doctor';
    return postData;
}

var teamData = null;

function edit() {
    /*$("#editBizAppFrom")[0].reset();*/
    if (selectedDataRow == null) {
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    if (selectedDataRow.dataStatus == 'pending_check') {
        toastr.error("这是待审核数据不能编辑");
        return;
    }

    VueObj.$set(VueObj.$data, "addBizApp", JSON.parse(JSON.stringify(selectedAppRow)));
    VueObj.$set(VueObj.$data, "editBizApp", JSON.parse(JSON.stringify(selectedDataRow)));
    $('#editBizApp').modal(true);
}


function doEditApp() {
    var postData = {};
    postData.id = selectedDataRow.id;
    postData.isvPid = selectedDataRow.isvPid;
    postData.refCode = selectedDataRow.refCode;
    postData.orgCode = selectedDataRow.orgCode;
    postData.bizCode = selectedDataRow.bizCode;
    postData.appCategory = selectedDataRow.appCategory;
    console.log(postData);
    $.ajax({
        type: 'post',
        url: basePath + 'bizApp/editDocBizApp',
        dataType: 'json',
        contentType: "application/json",
        beforeSend: function () {
            showLoading();
        },
        complete: function () {
            hideLoading();
        },
        data: JSON.stringify(postData),
        success: function (data) {
            if (data.result) {
                toastr.success(data.message);
                doRefresh();
                $("#editBizApp").modal('hide');
            } else {
                toastr.error(data.message);
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}


function beforePubish() {
    if (selectedDataRow == null) {
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    if (selectedDataRow.dataStatus == 'pending_check') {
        toastr.error("这是待审核数据不能提交发布");
        return;
    }

    if (selectedDataRow.dataStatus == 'check_pass') {
        toastr.error("这是已审核数据不能重复提交发布");
        return;
    }

    $.ajax({
        type: 'post',
        url: basePath + 'bizApp/beforePublish',
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify({appid: selectedDataRow.appid, appCategory: 'doctor'}),
        success: function (data) {
            if (data.result) {
                // publishApp();
                // 家庭医生 显示 二维码
                if(showQrCode == selectedDataRow.bizCode){
                    publishApp();
                }else{
                    swal({
                        title: '提示',
                        text: "确定要发布这个机构专家吗？",
                        showCancelButton:"true",
                        showConfirmButton:"true",
                        confirmButtonText:"确定",
                        cancelButtonText:"取消",
                        animation:"slide-from-top"
                    }, function() {
                        doPublishApp();
                    });
                }
            } else {
                toastr.error(data.message);
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}

function publishApp() {
    if (selectedDataRow == null) {
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    if (selectedDataRow.dataStatus == 'pending_check') {
        toastr.error("这是待审核数据不能提交发布");
        return;
    }

    if (selectedDataRow.dataStatus == 'check_pass') {
        toastr.error("这是已审核数据不能重复提交发布");
        return;
    }

    //
    // $.ajax({
    //     type: 'post',
    //     url: basePath + 'bizApp/updateQRCode',
    //     dataType: 'json',
    //     contentType: "application/json",
    //     beforeSend: function () {
    //         showLoading();
    //     },
    //     complete: function () {
    //         hideLoading();
    //     },
    //     data: JSON.stringify({
    //         id: selectedAppRow.id,
    //         appid: selectedDataRow.appid,
    //         docCode: selectedDataRow.refCode,
    //         orgCode: selectedDataRow.orgCode
    //         ,
    //         appCategory: selectedDataRow.appCategory
    //     }),
    //     success: function (data) {
    //         if (data.result) {
    //             // console.log(data.content)
    //             // //移除当前已生成数据
    //             $("#_validNum").text(data.content.validNum);
    //             $("#scanCode").attr("src", data.content.qrUrl);
    //             $("#publishApp").modal(true);
    //         } else {
    //             toastr.error(data.message);
    //         }
    //     },
    //     error: function (request) {
    //         toastr.error(common_system_error);
    //     }
    // });


    doShowQrCode( basePath + 'bizApp/updateQRCode',
        {
            id: selectedAppRow.id,
            appid: selectedDataRow.appid,
            docCode: selectedDataRow.refCode,
            orgCode: selectedDataRow.orgCode
            ,
            appCategory: selectedDataRow.appCategory
        }, 'minApp');
}

function chageQRCode() {
    if (selectedDataRow == null) {
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    if (selectedDataRow.dataStatus == 'pending_check') {
        toastr.error("这是待审核数据不能编辑");
        return;
    }

    $.ajax({
        type: 'post',
        url: basePath + 'bizApp/updateQRCode',
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify({
            id: selectedAppRow.id,
            appid: selectedAppRow.isvPid,
            docCode: selectedDataRow.refCode,
            orgCode: selectedRow.orgCode
        }),
        success: function (data) {
            if (data.result) {
                // console.log(data.content)
                //移除当前已生成数据
                $("#scanCode").attr("src", data.content);
            } else {
                toastr.error(data.message);
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}

function doPublishApp() {
    var postData = {};
    postData.id = selectedDataRow.id;
    postData.appid = selectedDataRow.appid;
    postData.isvPid = selectedDataRow.isvPid;
    postData.refCode = selectedDataRow.refCode;
    postData.bizCode = selectedDataRow.bizCode;
    postData.appCategory = selectedDataRow.appCategory;
    postData.status = selectedDataRow.status;
    postData.orgCode = selectedDataRow.orgCode;
    $.ajax({
        type: 'post',
        url: basePath + 'bizApp/publishDocBizApp',
        dataType: 'json',
        contentType: "application/json",
        beforeSend: function () {
            showLoading();
            $("#upPublish").button('loading');
        },
        complete: function () {
            hideLoading();
            $("#upPublish").button('reset');
        },
        data: JSON.stringify(postData),
        success: function (data) {
            if (data.result) {
                toastr.success(data.message);
                doRefresh();
                closeScanOrCodePage();
            } else {
                toastr.error(data.message);
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}


function unPublishAppwin() {
    if (selectedDataRow == null) {
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    if (selectedDataRow.status == 'unpublished') {
        toastr.error("这是未发布数据无需撤销");
        return;
    }
    if (selectedDataRow.dataStatus == 'pending_check') {
        toastr.error("这是待审核数据不能撤销");
        return;
    }
    $("input[name=error_text]").removeAttrs('checked');
    $("#error_textarea").val("");
    $("#unPublishAppWin").modal(true);
}

function doUnPublishApp() {
    var result = new Array();
    $("input[name=error_text]:checked").each(function (index, value) {
        result.push($(value).val());
    });
    if (result.length == 0 && $("#error_textarea").val() == '') {
        toastr.error("请选择撤销原因");
        return;
    }
    result.push($("#error_textarea").val());
    // if(result.length==0){
    //     toastr.error("请选择撤销原因");
    //     return;
    // }
    var postData = {};
    postData.id = selectedDataRow.id;
    postData.appid = selectedDataRow.appid;
    postData.isvPid = selectedDataRow.isvPid;
    postData.refCode = selectedDataRow.refCode;
    postData.bizCode = selectedDataRow.bizCode;
    postData.orgCode = selectedDataRow.orgCode;
    postData.appCategory = selectedDataRow.appCategory;
    postData.status = selectedDataRow.status;
    postData.revokeRemark = result.join(",");
    $.ajax({
        type: 'post',
        url: basePath + 'bizApp/unPublishDocBizApp',
        dataType: 'json',
        contentType: "application/json",
        beforeSend: function () {
            showLoading();
        },
        complete: function () {
            hideLoading();
        },
        data: JSON.stringify(postData),
        success: function (data) {
            if (data.result) {
                toastr.success(data.message);
                doRefresh();
                $("#unPublishAppWin").modal("hide");
            } else {
                toastr.error(data.message);
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}


function deleteBatchApp() {
    if (selectedDataRow == null) {
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    $("input[name=del_text]").removeAttrs('checked');
    $("#del_textarea").val("");

    if (selectedDataRow.dataStatus == 'pending_check') {
        toastr.error("这是待审核数据不能删除");
        return;
    }
    if (selectedDataRow.status == 'publish') {
        toastr.error("这是已发布数据，请先撤销再删除");
        return;
    }
    $("#delAppWin").modal(true);
}

function dodelApp() {
    var result = new Array();
    $("input[name=del_text]:checked").each(function (index, value) {
        result.push($(value).val());
    });
    if (result.length == 0 && $("#del_textarea").val() == '') {
        toastr.error("请选择撤销原因");
        return;
    }
    result.push($("#del_textarea").val());
    var postData = {};
    postData.id = selectedDataRow.id;
    postData.appid = selectedDataRow.appid;
    postData.isvPid = selectedDataRow.isvPid;
    postData.refCode = selectedDataRow.refCode;
    postData.bizCode = selectedDataRow.bizCode;
    postData.orgCode = selectedDataRow.orgCode;
    postData.appCategory = selectedDataRow.appCategory;
    postData.status = selectedDataRow.status;
    postData.dataStatus = 'delete';
    postData.remark = result.join(",");
    $.ajax({
        type: 'post',
        url: basePath + 'bizApp/delBizApp',
        dataType: 'json',
        contentType: "application/json",
        beforeSend: function () {
            showLoading();
        },
        complete: function () {
            hideLoading();
        },
        data: JSON.stringify(postData),
        success: function (data) {
            if (data.result) {
                toastr.success(data.message);
                doRefresh();
                $("#delAppWin").modal('hide');
            } else {
                toastr.error(data.message);
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}

function updateChildrenBiz() {
    if (selectedDataRow == null) {
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }

    console.log(selectedAppRow);
    var tableOptions = $("#dataTable").bootstrapTable('getOptions', null);
    window.location.href = basePath + "bizApp/bizDocChildrenBiz?appid=" + selectedDataRow.appid + "&t=" + new Date().getTime() +
        "&searchStr=" + searchStrBefore("#searchForm", "#dataAppTable") + searchStrBefore("#search2")
        + ',spageNo=' + tableOptions.pageNumber + ',spageSize=' + tableOptions.pageSize
        + ',bizCode=' + $.trim($('#sbizCode').val())
        + ',orgCode=' + $.trim($('#sorgCode').val())
        + ',isvPid=' + $.trim($('#sisvPid').val())
        + ',sappid=' + selectedAppRow.appid
        + '&isvPid=' + (selectedDataRow.isvPid?selectedDataRow.isvPid:"")
        + '&refCode=' + (selectedDataRow.refCode?selectedDataRow.refCode:"")
        + '&orgCode=' + (selectedDataRow.orgCode?selectedDataRow.orgCode:"")
        + '&bizParentCode=' + (selectedDataRow.bizCode?selectedDataRow.bizCode:"")
        + '&bizParentName=' + (selectedDataRow.bizName?selectedDataRow.bizName:"")
        + '&thirdBizName=' + (selectedDataRow.bizName?selectedDataRow.bizName:"")
        + '&thirdOrgName=' + (selectedDataRow.orgName?selectedDataRow.orgName:"")
        + '&thirdDocName=' + (selectedDataRow.docName?selectedDataRow.docName:"")
        + '&thirdIsvName=' + (selectedDataRow.isvName?selectedDataRow.isvName:"")
        + '&sortNum=' + (selectedDataRow.sortNum?selectedDataRow.sortNum:"")
        +'&isTeamExist=' + searchInfo.isTeamExist + '&isOrgExist=' + searchInfo.isOrgExist;
}

function downaload() {
    if (selectedAppRow == null) {
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    $('#searchForm').attr("action", basePath + "bizApp/exportDocBizAppExcel");
    $('#searchForm').submit();
}

function publishDataStatus(value, row, index) {
    console.log(selectedAppRow.appid);
    return PushlishStatus[value];
}

function dataStatus(value, row, index) {
    return DataStatus[value];
}


function checkTypeFormatter(value, row, index) {
    if (resultTypeMap != null) {
        return resultTypeMap[value];
    }
    return "";
}

// 默认选中事件
var refresh = 0;

function handleServerResult(res) {
    if (refresh == 0 && appid != null && appid != 'null') {
        if (res.list.length > 0)
            for (var i = 0; i < res.list.length; i++) {
                if (res.list[i].appid == appid) {
                    selectedAppRow = res.list[i];
                    // 查询条件的赋值
                    $("#sbizCode").val(selectedAppRow.bizCode);
                    $("#sorgCode").val(selectedAppRow.refCode);
                    $("#sisvPid").val(selectedAppRow.isvPid);
                }
            }
        doRefresh();
        refresh++;
    }
    return {
        "total": res.total,//总页数
        "rows": res.list   //数据
    };
}

var index = null;

function onceCheck(value, row, $elem) {
    if (refresh == 1 && appid != null && appid != 'null' && row.appid == appid) {
        index = $elem;
        setTimeout(function () {
            $("#dataAppTable > tbody > tr[data-index='" + index + "']").addClass("success");
            selectedAppRow = row;
            $("#sbizCode").val(selectedAppRow.bizCode);
            $("#sorgCode").val(selectedAppRow.refCode);
            $("#sisvPid").val(selectedAppRow.isvPid);
            //右侧的刷新
            doRefresh();
        }, 500);
        refresh++;
    }
    return value;
}

function refreshQrCode() {
    doShowQrCode( basePath + 'bizApp/updateQRCode',
        {
            id: selectedAppRow.id,
            appid: selectedDataRow.appid,
            docCode: selectedDataRow.refCode,
            orgCode: selectedDataRow.orgCode
            ,
            appCategory: selectedDataRow.appCategory
        }, 'minApp');
}



function closeScanOrCodePage() {
    $("#scanQrCodePage-common").modal('hide');
    $("#scanCodeMinApp").attr("src", '');
}